//
//  UIButton+Space.m
//  Backhome
//
//  Created by vbn on 2017/3/8.
//  Copyright © 2017年 LeiXiao CQ. All rights reserved.
//

#import "UIButton+KNSpace.h"
#import "objc/runtime.h"

@implementation UIButton (KNSpace)

- (void)setUnreadView:(UIView *)unreadView {
    objc_setAssociatedObject(self, @selector(unreadView), unreadView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)unreadView {
    return objc_getAssociatedObject(self, @selector(unreadView));
}

-(void)KNCenterButtonAndImageWithSpacing:(CGFloat)spacing {
    self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
}

- (void)KNCenterImageAndTitle:(float)spacing
{
    // get the size of the elements here for readability
    CGSize imageSize = self.imageView.frame.size;
    CGSize titleSize = self.titleLabel.frame.size;
    
    // get the height they will take up as a unit
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
    
    // raise the image and push it right to center it
    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
    
    // lower the text and push it left to center it
    self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);
}

- (void)KNSetUnreadFrame:(CGRect)frame {
    self.unreadView.frame = frame;
    self.unreadView.layer.cornerRadius = frame.size.width/2;
}

- (void)KNSetUnread:(BOOL)unread {
    if (!self.unreadView) {
        self.unreadView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.bounds) - 5, CGRectGetMinY(self.bounds) +3, 5, 5)];
        self.unreadView.backgroundColor = [UIColor redColor];
        self.unreadView.layer.masksToBounds = YES;
        self.unreadView.layer.cornerRadius = 2.5;
        self.unreadView.userInteractionEnabled = NO;
        [self addSubview:self.unreadView];
    }
    self.unreadView.hidden = !unread;
}

- (void)KNImageLeftToRight:(float)space {
    self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView.frame.size.width, 0, self.imageView.frame.size.width);
    self.imageEdgeInsets = UIEdgeInsetsMake(0, self.titleLabel.frame.size.width + space, 0, -(self.titleLabel.frame.size.width + space));
}

- (void)KNImageLeftToRight {
    [self KNImageLeftToRight:0];
}


@end
